#!/bin/bash

# MySQL安装和项目启动脚本
echo "🚀 MySQL安装 + 停车场管理系统启动"
echo "================================="

# 检查是否已安装Homebrew
if ! command -v brew &> /dev/null; then
    echo "❌ Homebrew未安装，正在安装..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
fi

# 安装MySQL
echo "📦 安装MySQL..."
brew install mysql@8.0

# 启动MySQL服务
echo "🔧 启动MySQL服务..."
brew services start mysql@8.0

# 等待MySQL启动
echo "⏳ 等待MySQL启动..."
sleep 5

# 设置root密码
echo "🔑 设置MySQL root密码..."
mysql -uroot -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root123123';" 2>/dev/null || {
    echo "⚠️  密码可能已经设置，尝试连接..."
}

# 创建数据库
echo "📁 创建数据库..."
mysql -uroot -proot123123 -e "CREATE DATABASE IF NOT EXISTS \`park-management\` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"

# 导入SQL文件
echo "📊 导入数据库结构..."
if [ -f "script/sql/ry_vue_5.X.sql" ]; then
    mysql -uroot -proot123123 park-management < script/sql/ry_vue_5.X.sql
    echo "✅ 数据库初始化完成"
else
    echo "❌ 数据库文件不存在: script/sql/ry_vue_5.X.sql"
    exit 1
fi

# 安装Redis
echo "📦 安装Redis..."
brew install redis
brew services start redis

# 检查Java版本
echo "🔍 检查Java版本..."
if ! java -version 2>&1 | grep -q "17"; then
    echo "⚠️  Java 17未激活，正在切换..."
    ./switch-to-java17.sh
fi

# 构建项目
echo "🔨 构建项目..."
mvn clean install -DskipTests

if [ $? -ne 0 ]; then
    echo "❌ 项目构建失败"
    exit 1
fi

# 启动应用
echo "🎯 启动应用..."
echo "应用将在: http://localhost:8080"
echo "默认账号: admin / admin123"
echo "按 Ctrl+C 停止应用"
echo "================================="

# 启动Spring Boot应用
mvn spring-boot:run -Dspring-boot.run.profiles=dev -pl park-admin